﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Configuration;

namespace Collector
{
    public class XmlHelper
    {
        /// <summary>
        /// 读取配置文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="configPath"></param>
        /// <returns></returns>
        public static bool GetConfig<T>(string configPath, ref T _configInfo)
        {
            if (!File.Exists(configPath))
                return false;
            //throw new Exception("The config file does not exist");
            XmlSerializer xml = new XmlSerializer(typeof(T));
            using (StreamReader sr = new StreamReader(configPath))
            {
                var obj = xml.Deserialize(sr);
                sr.Close();
                _configInfo = (T)obj;
                return true;
            }
        }
        /// <summary>
        /// 将XML字符串转成指定对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strXml"></param>
        /// <returns></returns>
        public static T Xml2Entity<T>(string strXml)
        {
            try
            {
                XmlSerializer xml = new XmlSerializer(typeof(T));
                var obj = xml.Deserialize(new StringReader(strXml));
                if (obj is T)
                    return (T)obj;
                return default(T);
            }
            catch (Exception ex)
            {
                throw new Exception("类型转换失败!" + ex.Message);
            }

        }

        public static string XmlSerialize<T>(T obj)
        {
            //去掉默认命名空间
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");

            string xmlString = string.Empty;
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream())
            {
                xmlSerializer.Serialize(ms, obj, ns);
                xmlString = Encoding.UTF8.GetString(ms.ToArray());
            } return xmlString;
        }
        /// <summary>
        /// 保存配置文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="config"></param>
        /// <param name="savepath"></param>
        public static void SaveConfig<T>(T config, string savepath)
        {
            XmlSerializer xml = new XmlSerializer(typeof(T));
            using (StreamWriter sw = new StreamWriter(savepath))
            {
                xml.Serialize(sw, config);
                sw.Close();
            }
        }

        public static void SetApplicationConfig(string key, string value)
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            if (config.AppSettings.Settings[key] != null)
                config.AppSettings.Settings[key].Value = value;
            else
                config.AppSettings.Settings.Add(key, value);

            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }

        public static string GetApplicationConfig(string key, string def)
        {
            string obj = System.Configuration.ConfigurationManager.AppSettings[key];
            if (obj != null && !string.IsNullOrWhiteSpace(obj))
                return obj;

            if (def != null && !string.IsNullOrWhiteSpace(def))
                return def;
            return "";
        }
    }
}
